package com.lzy.webapi.controller;

import com.github.pagehelper.PageInfo;
import com.lzy.framework.core.ensure.Ensure;
import com.lzy.framework.core.orm.db.Pager;
import com.lzy.framework.core.output.Result;
import com.lzy.framework.core.utils.DozerUtils;
import com.lzy.product.apis.OrderProductServiceApi;
import com.lzy.product.common.util.EnumUtil;
import com.lzy.product.constants.BusinessType;
import com.lzy.product.dtos.OrderProductDto;
import com.lzy.sms.constants.BusiTypeEnum;
import com.lzy.sms.constants.CommonConstants;
import com.lzy.sms.dtos.CodeDTO;
import com.lzy.webapi.component.Auth;
import com.lzy.webapi.component.UserToken;
import com.lzy.webapi.facade.OrderFacade;
import com.lzy.webapi.request.*;
import com.lzy.webapi.response.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by WIN7 on 2017/12/6.
 */
@Controller
@RequestMapping("api/order")
public class OrderController extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private OrderFacade orderFacade;
    @Autowired
    private OrderProductServiceApi orderProductServiceApi;

    /**
     * 生成验证码
     *
     * @param phone
     * @return
     */
    @RequestMapping(value = "/generateCode", method = RequestMethod.POST)
    @ResponseBody
    public Result generateCode(String phone) {
        //发送验证码
        Boolean ok = orderFacade.generateCode(phone);
        Ensure.that(ok).isTrue("04000005");
        return new Result();
    }

    /**
     * 验证验证码
     *
     * @param token
     * @param request
     * @return
     */
    @RequestMapping(value = "verifyAuthInfo", method = RequestMethod.POST)
    @ResponseBody
    public Result verifyAuthInfo(@RequestHeader("token") String token, OrderProductRequest request) {
        Ensure.that(request).isNotNull("04000001");
        isLogin(token);
        //验证码验证
        CodeDTO codeDTO = new CodeDTO();
        codeDTO.setAuthTarget(request.getPhone());
        codeDTO.setAuthType(BusiTypeEnum.PRODUCT_ORDER_VERIFY.getVal());
        codeDTO.setWay(CommonConstants.MediaWay.PHONE);
        codeDTO.setAuthCode(request.getCode());
        Ensure.that(orderFacade.verifyAuthInfo(codeDTO)).isTrue("04000006");
        return new Result();
    }

    /**
     * 生成产品订单
     *
     * @param token
     * @param request
     * @return
     */
    @RequestMapping(value = "create", method = RequestMethod.POST)
    @ResponseBody
    public Result createOrder(@RequestHeader("token") String token, OrderProductRequest request) {
        Ensure.that(request).isNotNull("04000001");
        UserToken ut = isLogin(token);
        OrderProductDto orderProductDto = DozerUtils.map(request, OrderProductDto.class);
        orderProductDto.setCreateUser(ut.getUserId());
        LOGGER.info("客户姓名" + request.getName() + "客户地址" + request.getPhone());
        OrderProductDto orderProduct = orderFacade.createOrderProduct(orderProductDto);
        Ensure.that(orderProduct).isNotNull("04000002");
        Result result = new Result();
        result.setResult(DozerUtils.map(orderProduct, OrderProductCreateResponse.class));
        return result;
    }

    /**
     * 获取支付二维码地址
     *
     * @param token
     * @param request
     * @return
     */
    @RequestMapping(value = "payCode", method = RequestMethod.GET)
    @ResponseBody
    public Result payCode(@RequestHeader("token") String token, OrderPayCodeRequest request) {
        Ensure.that(request).isNotNull("04000001");
        isLogin(token);
        OrderProductDto orderProductDto = DozerUtils.map(request, OrderProductDto.class);
        OrderProductDto orderProduct = orderFacade.payCode(orderProductDto);
        Ensure.that(orderProduct).isNotNull("04000009");
        Result result = new Result();
        result.setResult(orderProduct.getPayCode());
        return result;
    }

    /**
     * 编辑订单
     *
     * @param token
     * @param request
     * @return
     */
    @RequestMapping(value = "update", method = RequestMethod.POST)
    @ResponseBody
    public Result updateOrder(@RequestHeader("token") String token, OrderProductRequest request) {
        Ensure.that(request).isNotNull("04000001");
        UserToken ut = isLogin(token);
        OrderProductDto orderProductDto = DozerUtils.map(request, OrderProductDto.class);
        orderProductDto.setUpdateUser(ut.getUserId());
        orderProductDto.setContractVerify(BusinessType.VerifyStatusEnum.VERIFY.getK());
        Ensure.that(orderFacade.updateOrderProduct(orderProductDto)).isTrue("04000004");
        return new Result();
    }

    /**
     * 查询产品订单列表
     *
     * @param token
     * @param request
     * @return
     */
    @RequestMapping(value = "list", method = RequestMethod.GET)
    @ResponseBody
    public Result orderList(@RequestHeader("token") String token, OrderProductRequest request) {
        Ensure.that(request).isNotNull("04000001");
        UserToken ut = isLogin(token);
        Result result = new Result();
        Pager pager = new Pager();
        pager.setPageNum(request.getPageNum());
        pager.setPageSize(request.getPageSize());
        OrderProductDto orderProductDto = DozerUtils.map(request, OrderProductDto.class);
        orderProductDto.setCreateUser(ut.getUserId());
        orderProductDto.setType(BusinessType.OrderProductType.PRODUCT.getCode());
        PageInfo pageInfo = orderFacade.orderProductList(pager, orderProductDto);
        if (pageInfo != null) {
            result.setResult(DozerUtils.maps(pageInfo.getList(), OrderProductListResponse.class));
        }
        return result;
    }

    /**
     * 查看产品订单详情
     *
     * @param token
     * @param orderId
     * @return
     */
    @RequestMapping(value = "detail/{orderId}", method = RequestMethod.GET)
    @ResponseBody
    public Result orderProductDetail(@RequestHeader("token") String token, @PathVariable("orderId") Long orderId) {
        Ensure.that(orderId).isNotNull("04000001");
        isLogin(token);
        Result result = new Result();
        OrderProductDetailResponse orderProductDetailResponse = orderFacade.orderProductDetail(orderId);
        if (orderProductDetailResponse != null) {
            if (orderProductDetailResponse.getStatus() != null) {
                BusinessType.OrderType orderType = EnumUtil.valueOf(BusinessType.OrderType.class, orderProductDetailResponse.getStatus());
                if (orderType != null) {
                    orderProductDetailResponse.setStatusName(orderType.getDesc());
                }
            }
            result.setResult(orderProductDetailResponse);
        }
        return result;
    }

    /**
     * 查看产品订单支付状态
     *
     * @param token
     * @param orderId
     * @return
     */
    @RequestMapping(value = "status/{orderId}", method = RequestMethod.GET)
    @ResponseBody
    public Result getStatus(@RequestHeader("token") String token, @PathVariable("orderId") Long orderId) {
        Ensure.that(orderId).isNotNull("04000001");
        isLogin(token);
        OrderProductDto orderProductDto = orderFacade.getStatus(orderId);
        if (orderProductDto != null) {
            return new Result(orderProductDto.getStatus());
        }
        return new Result();
    }

    /**
     * 查询卡券宝订单列表
     *
     * @param token
     * @param request
     * @return
     */
    @RequestMapping(value = "couponsList", method = RequestMethod.GET)
    @ResponseBody
    public Result orderCouponsList(@RequestHeader("token") String token, OrderProductRequest request) {
        Ensure.that(request).isNotNull("04000001");
        UserToken ut = isLogin(token);
        Result result = new Result();
        Pager pager = new Pager();
        pager.setPageNum(request.getPageNum());
        pager.setPageSize(request.getPageSize());
        OrderProductDto orderProductDto = DozerUtils.map(request, OrderProductDto.class);
        orderProductDto.setCreateUser(ut.getUserId());
        orderProductDto.setType(BusinessType.OrderProductType.COUPONS.getCode());
        PageInfo pageInfo = orderFacade.orderCouponsList(pager, orderProductDto);
        if (pageInfo != null) {
            result.setResult(DozerUtils.maps(pageInfo.getList(), OrderCouponsListResponse.class));
        }
        return result;
    }
    /**
     * 查询卡券宝订单详情
     *
     * @param token
     * @param orderId
     * @return
     */
    @RequestMapping(value = "couponsDetail/{orderId}", method = RequestMethod.GET)
    @ResponseBody
    public Result orderCouponsDetail(@RequestHeader("token") String token, @PathVariable("orderId") Long orderId) {
        Ensure.that(orderId).isNotNull("04000001");
        isLogin(token);
        Result result = new Result();
        OrderCouponsDetailResponse orderCouponsDetailResponse = orderFacade.orderCouponsDetail(orderId);
        if (orderCouponsDetailResponse != null){
            result.setResult(orderCouponsDetailResponse);
        }
        return result;
    }

    /**
     * 关闭订单
     *
     * @param token
     * @return
     */
    @RequestMapping(value = "closeOrder/{orderId}", method = RequestMethod.POST)
    @ResponseBody
    public Result updateOrder(@RequestHeader("token") String token,@PathVariable Long orderId) {
        UserToken ut = isLogin(token);
        OrderProductDto orderProductDto = new OrderProductDto();
        orderProductDto.setOrderId(orderId);
        orderProductDto.setUpdateUser(ut.getUserId());
        orderProductDto.setStatus(BusinessType.CouponOrderType.CLOSED.getCode());
        Ensure.that(orderFacade.updateOrderProduct(orderProductDto)).isTrue("04000004");
        return new Result();
    }

    /**
     * 销售订单
//     * @param token
     * @return
     */
    @RequestMapping(value = "saleOrder", method = RequestMethod.GET)
    @ResponseBody
    public Result saleOrder(@RequestHeader("token") String token){
        UserToken ut = isLogin(token);
        Long saleMemberId = ut.getUserId();
//        Long saleMemberId = 86956L;
        SaleOrderResponse saleOrderResponse = orderFacade.saleOrder(saleMemberId);
        if(saleOrderResponse != null){
            return new Result(saleOrderResponse);
        }
        return new Result();
    }

    /**
     * 销售订单列表
//     * @param token
     * @param saleOrderRequest
     * @return
     */

    @RequestMapping(value = "saleOrderList", method = RequestMethod.GET)
    @ResponseBody
    public Result saleOrderList(@RequestHeader("token") String token,SaleOrderRequest saleOrderRequest){
        UserToken ut = isLogin(token);
//        销售商会员id
        Long saleMemberId = ut.getUserId();
//        Long saleMemberId = 86956L;
        Pager pager = new Pager();
        pager.setPageNum(saleOrderRequest.getPageNum());
        pager.setPageSize(saleOrderRequest.getPageSize());
        SaleOrderListResponse saleOrderListResponse = orderFacade.saleOrderList(pager,saleMemberId,saleOrderRequest.getMotorId(),saleOrderRequest.getStartTime(),saleOrderRequest.getEndTime(),saleOrderRequest.getStatus());
        return new Result(saleOrderListResponse);
    }

    /**
     * 获取销售订单详情
     * @param token
     * @param orderId
     * @return
     */
    @RequestMapping(value = "saleOrderDetail/{orderId}", method = RequestMethod.GET)
    @ResponseBody
    public Result saleOrderDetail(@RequestHeader("token") String token,@PathVariable Long orderId){
        Ensure.that(orderId).isNotNull("04000001");
        isLogin(token);
        SaleOrderDetailResponse saleOrderDetailResponse = orderFacade.saleOrderDetail(orderId);
//        SaleOrderDetailResponse saleOrderDetailResponse = orderFacade.saleOrderDetail(9111011570411009999L);
        return new Result(saleOrderDetailResponse);
    }

    /**
     * 补贴-销售-代理销售明细
//     * @param token
     * @return
     */
    @Auth
    @RequestMapping(value = "subsidy", method = RequestMethod.GET)
    @ResponseBody
    public Result subdify(@RequestHeader("token") String token, SaleSubsidyRequest request){
        Ensure.that(request).isNotNull("04000001");
        UserToken ut = isLogin(token);
        Long saleMemberId = ut.getUserId();
        Pager pager = new Pager();
        pager.setPageNum(request.getPageNum());
        pager.setPageSize(request.getPageSize());
        List<SaleSubsidyResponse> saleSubsidyResponseList = orderFacade.subsidy(pager,saleMemberId,request.getType(),request.getStatus());
        if(saleSubsidyResponseList != null && saleSubsidyResponseList.size() > 0){
            return new Result(saleSubsidyResponseList);
        }
        return new Result();
    }

    /**
     * 获取代理商列表
     * @return
     */
    @Auth
    @RequestMapping(value = "agentList", method = RequestMethod.GET)
    @ResponseBody
    public Result getAgentList(@RequestHeader("token") String token,AgentSaleRequest request){
        UserToken ut = isLogin(token);
        Ensure.that(request).isNotNull("");
        Pager pager = new Pager();
        pager.setPageNum(request.getPageNum());
        pager.setPageSize(request.getPageSize());
//        AgentResponse agentResponse = orderFacade.getAgentList(pager,86956L);
        AgentResponse agentResponse = orderFacade.getAgentList(pager,ut.getUserId());
        return new Result(agentResponse);
    }

    /**
     * 根据userId获取销售记录
     */
    @RequestMapping(value = "saleList", method = RequestMethod.GET)
    @ResponseBody
    public Result getSaleList(AgentSaleRequest request){
        Ensure.that(request).isNotNull("");
        Ensure.that(request.getId()).isNotNull("");
        Pager pager = new Pager();
        pager.setPageNum(request.getPageNum());
        pager.setPageSize(request.getPageSize());
        AgentSaleRecordResponse agentSaleRecordResponse = orderFacade.getSaleList(pager,request.getId());
        return new Result(agentSaleRecordResponse);
    }

    /**
     * 代理商销售记录
//     * @param token
     *
     * @return
     */
    @Auth
    @RequestMapping(value = "/queryAgentSaleRecordList", method = RequestMethod.GET)
    @ResponseBody
    public Result queryAgentSaleRecordList(@RequestHeader("token") String token,AgentSaleRecordRequest request) {
        Ensure.that(request).isNotNull("");
        UserToken ut = isLogin(token);
        Ensure.that(request).isNotNull("");
        Ensure.that(request.getTimeStr()).isNotNull("");
        Ensure.that(request.getType()).isNotNull("");
        Pager pager = new Pager();
        pager.setPageNum(request.getPageNum());
        pager.setPageSize(request.getPageSize());
        AgentRecordResponse agentRecordResponse = orderFacade.queryAgentSaleRecordList(pager,ut.getUserId(),request.getType(),request.getTimeStr());
//        AgentRecordResponse agentRecordResponse = orderFacade.queryAgentSaleRecordList(pager,86956L,request.getType(),request.getTimeStr());
        return new Result(agentRecordResponse);
    }

}
